import time
from datetime import datetime, timedelta

from flask import render_template, request, session, redirect, url_for, g, current_app, jsonify, abort

from application import constants, db
from application.models import User, News, Category
from application.utils.common import user_login_data
from application.utils.image_storage import storage
from application.utils.response_code import RET
from . import admin_blue


@admin_blue.before_request
def check_admin():
    """
    管理员的权限验证
    :return:
    """

    is_admin = session.get("is_admin", False)
    if not is_admin and not request.url.endswith("/admin/login"):
        return redirect("/")


@admin_blue.route("/index")
@user_login_data
def index():
    """
    后台主页面
    :return:
    """
    # 判断是否是管理员,如果不是,直接跳转到首页
    user = g.user
    data = {
        "user": user.to_dict()
    }
    return render_template("admins/index.html", data=data)


@admin_blue.route("/login", methods=["GET", "POST"])
@user_login_data
def login():
    """
    后台登陆界面
        1.获取参数
        2.校验参数
        3.查询当前用户
        4.校验登陆的账户名密码
        5.保存用户登陆信息
    :return:
    """
    if request == "GET":
        # 判断当前是否有登陆,如果有登陆直接重定向到管理员后台主页
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", False)
        if user_id and is_admin:
            return render_template("admins/index.html")
        else:
            # 没有登陆,跳转到登陆界面
            return render_template("admins/login.html")

    else:
        # 1.获取参数
        username = request.form.get("username")
        password = request.form.get("password")

        # 2.校验参数
        if not all([username, password]):
            return render_template("admins/login.html", errmsg="参数错误")

        # 3.查询当前用户
        try:
            user = User.query.filter(User.mobile == username, User.is_admin == True).first()
        except Exception as e:
            return render_template("admins/login.html", errmsg="用户查询失败")

        if not user:
            return render_template("admins/login.html", errmsg="未查询到用户信息")

        # 4.校验登陆的账户名密码
        if not user.check_passowrd(password):
            return render_template("admins/login.html", errmsg="用户名或密码错误")

        # 5.保存用户登陆信息
        session['user_id'] = user.id
        session["mobile"] = user.mobile
        session["nick_name"] = user.nick_name
        session["is_admin"] = user.is_admin

        # 跳转到后台管理首页
        return redirect(url_for("admin.index"))


@admin_blue.route("/user_count")
def user_count():
    """
    用户数据统计
    :return:
    """

   # 总人数
    total_count = 0  # 总人数
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 月新增人数
    mon_count = 0  # 月新增人数
    try:
        now = time.localtime()  # 本地时间
        mon_begin = "%d-%02d-01" % (now.tm_year, now.tm_mon)
        mon_begin_date = datetime.strptime(mon_begin, "%Y-%m-%d")
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 日新增人数
    day_count = 0  # 日新增人数
    try:
        day_begin = "%d-%02d-%02d" % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.strptime(day_begin, "%Y-%m-%d")
        day_count = User.query.filter(User.is_admin == False, User.create_time >= day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)


    # 查询图标信息

    # 获取当天00:00:00的时间
    now_begin = "%d-%02d-%02d" % (now.tm_year, now.tm_mon, now.tm_mday)
    now_date = datetime.strptime(now_begin, "%Y-%m-%d")
    # now_date = datetime.strptime(datetime.now().strftime("%Y-%m-%d"), "%Y-%m-%d")
    # datetime.now()
    # 定义空数组，保存数据
    active_date = []
    active_count = []

    # 依次添加数据，再反转
    for i in range(0,31):
        begin_date = now_date - timedelta(days = i)
        end_date = now_date - timedelta(days = i- 1)
        active_date.append(begin_date.strftime('%m/%d'))

        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date, User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)

    active_date.reverse()
    active_count.reverse()

    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_date" : active_date,
        "active_count" : active_count
    }
    return render_template("admins/user_count.html", data=data)


@admin_blue.route("/user_list")
def user_list():
    """
    用户列表
    :return:
    """
    # 获取参数
    page = request.args.get("page", 1)

    # 校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user_list = []
    current_page = 1
    total_page = 1

    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.create_time.desc()) .paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        user_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []
    for user in user_list:
        user_dict_li.append(user.to_admin_dict())


    data = {
        "users" : user_dict_li,
        "current_page" : current_page,
        "total_page" : total_page
    }

    return render_template("admins/user_list.html", data = data)

@admin_blue.route("/news_review")
def review_list():
    """
    返回待审核新闻列表/搜索功能
    :return:
    """
    page = request.args.get("page", 1)
    keywords = request.args.get("keywords", None)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1
    filters = [News.status != 0]

    # 如果关键字存在,就进行关键字搜索
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    new_dict_li = []
    for news in news_list:
        new_dict_li.append(news.to_review_dict())

    data = {
        "current_page" : current_page,
        "total_page" : total_page,
        "news_list" : new_dict_li
    }

    return render_template("admins/news_review.html", data = data)


@admin_blue.route("/news_review_detail/<int:news_id>")
def news_review_detail(news_id):
    """
    新闻审核详情
    :param news_id:
    :return:
    """

    # 通过ID查询新闻
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logget.error(e)

    if not news:
        data = {
            "errmsg" : "未查询到此新闻"
        }
        return render_template("admins/news_review_detail.html", data =data )


    data = {
        "news" : news.to_dict()
    }


    return render_template("admins/news_review_detail.html", data = data)


@admin_blue.route("/news_review_action", methods=["POST"])
def news_review_action():
    """
    新闻审核是否通过逻辑
        1.获取参数
        2.校验参数
    :return:
    """

    # 1.获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 2.校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    if action not in("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logget.error(e)

    # 查询指定新闻数据
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logget.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

    if action =="accept":
        news.status = 0
    else:
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="请输入拒绝原因")
        news.status = -1
        news.reason = reason

    return jsonify(errno=RET.OK, errmsg="操作成功")


@admin_blue.route("/news_edit", methods=["GET","POST"])
def news_edit():
    """
    新闻板式编辑/搜索功能
    :return:
    """
    page = request.args.get("page", 1)
    keywords = request.args.get("keywords", None)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1
    filters = [News.status == 0]

    # 如果关键字存在,就进行关键字搜索
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    new_dict_li = []
    for news in news_list:
        new_dict_li.append(news.to_basic_dict())

    data = {
        "current_page" : current_page,
        "total_page" : total_page,
        "news_list" : new_dict_li
    }

    return render_template("admins/news_edit.html", data = data)

@admin_blue.route("/news_edit_detail", methods=["GET","POST"])
def news_edit_detail():
    """
    新闻编辑详情
    :return:
    """
    # 获取参数
    if request.method == "GET":
        news_id = request.args.get("news_id")

        if not news_id:
            abort(404)

        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admins/news_edit_detail.html", errmsg="参数错误")

        # 查询新闻
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admins/news_edit_detail.html", errmsg="查询数据错误")

        if not news:
            return render_template("admins/news_edit_detail.html", errmsg="未查询到数据")

        # 查询分类数据
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admins/news_edit_detail.html", errmsg="查询数据错误")

        category_dict_li = []

        for category in categories:
            # 取到分类的字典
            cate_dict = category.to_dict()

            # 判断当前遍历到的分类是否是当前新闻的分类,如果是则添加is_selected为True
            if category.id == news.category_id:
                cate_dict["is_selected"] = True
            category_dict_li.append(category.to_dict())

        # 移除最新分类
        category_dict_li.pop(0)

        data = {
                "news" : news.to_dict(),
                "categories" : category_dict_li
            }

        return render_template("admins/news_edit_detail.html", data= data)
    else:
        # 取到post进来的数据
        news_id = request.form.get("news_id")
        title = request.form.get("title")
        digest = request.form.get("digest")
        content = request.form.get("content")
        index_image = request.files.get("index_image")
        category_id = request.form.get("category_id")

        # 校验参数
        if not all([title, digest, content, category_id]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        # 获取新闻
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

        if not news:
            return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")

        # 1.2 尝试读取图片
        if index_image:
            try:
                index_image = index_image.read()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

            # 2. 将标题图片上传到七牛
            try:
                key = storage(index_image)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")
            news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

        # 3. 设置相关数据
        news.title = title
        news.digest = digest
        news.content = content
        news.category_id = category_id

        return jsonify(errno=RET.OK, errmsg="编辑成功")


@admin_blue.route("/news_type", methods=["GET","POST"])
def news_type():
    """
    新闻分类
    :return:
    """
    if request.method == "GET":
        # 查询分类数据
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admins/news_edit_detail.html", errmsg="查询数据错误")

        category_dict_li = []

        for category in categories:
            category_dict_li.append(category.to_dict())

        # 移除最新分类
        category_dict_li.pop(0)

        data = {
            "categories": category_dict_li
        }

        return render_template("admins/news_type.html", data = data)
    else:
        # 新增或者修改分类
        # 获取参数
        category_name = request.json.get("name")
        cid = request.json.get("id")

        if not category_name:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        if cid:
            try:
                cid = int(cid)
                category = Category.query.get(cid)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

            if not category:
                return jsonify(errno=RET.NODATA, errmsg="未查询到分类数据")

            category.name = category_name
        else:
            category = Category()
            category.name = category_name
            db.session.add(category)

        return jsonify(errno=RET.OK, errmsg="OK")